import type { App } from 'vue'
import type { RouteRecordRaw } from 'vue-router'
import { createRouter, createWebHistory } from 'vue-router'
import remainingRouter from './modules/remaining'
import { qiankunWindow } from 'vite-plugin-qiankun/es/helper'

// 创建路由实例
const router = createRouter({
  history: createWebHistory(), // createWebHashHistory URL带#，createWebHistory URL不带#
  strict: true,
  routes: remainingRouter as RouteRecordRaw[],
  scrollBehavior: () => ({ left: 0, top: 0 })
})

export const resetRouter = (): void => {
  const resetWhiteNameList = ['Redirect', 'Login', 'NoFind', 'Root']
  router.getRoutes().forEach((route) => {
    const { name } = route
    if (name && !resetWhiteNameList.includes(name as string)) {
      router.hasRoute(name) && router.removeRoute(name)
    }
  })
}

/**
 * 递归拉平路由（处理嵌套路由）
 * @param routes 路由配置
 * @param prefix 要添加的前缀
 * @param parentPath 父级路径
 */
const flattenRoutes = (
  routes: AppRouteRecordRaw[],
  prefix: string = '',
  parentPath: string = ''
): AppRouteRecordRaw[] => {
  return routes.flatMap(route => {
    // 处理路径
    const fullPath = `${parentPath}${route.path.startsWith('/') ? route.path : `/${route.path}`}`
    const prefixedPath = `${prefix}${fullPath}`

    // 创建新路由对象
    const newRoute: AppRouteRecordRaw = {
      ...route,
      path: prefixedPath,
      // 处理路由名称避免冲突
      name: route.name ? `${prefix.replace(/\//g, '_')}_${String(route.name)}` : undefined,
      meta: {
        ...route.meta,
        // 标记原始路径用于调试
        originalPath: fullPath
      }
    }

    // 移除children，确保路由是平的
    delete newRoute.children

    // 处理子路由（递归拉平）
    const childRoutes = route.children
      ? flattenRoutes(route.children, prefix, fullPath)
      : []

    return [newRoute, ...childRoutes]
  })
}

export const setupRouter = (
  app: App<Element>,
  options: {
    baseRouterPrefix?: string
  } = {}
) => {
  // 如果是乾坤环境且需要添加前缀
  if (qiankunWindow.__POWERED_BY_QIANKUN__) {
    const prefix = options.baseRouterPrefix || ''

    // 添加路由前缀（仅处理一级路由）
    const routers = flattenRoutes(remainingRouter, prefix);
    // 清空原有路由
    resetRouter()

    // 添加带前缀的路由
    routers.forEach((route) => {
      router.addRoute(route as RouteRecordRaw)
    })
  }
  app.use(router)
}

export default router
